const http = require('http')
const url = require('url')
// 路由
const routes = []
function reqRoute(path) {
    const keys = []
    if (path.includes(':')) {
        // path 转换成 /users/([^/]+)/([^/]+)
        path = path.replace(/:([^\/]+)/g, ($0, $1) => {
            keys.push($1)
            return '([^\/]+)'
        })
    }
    return {
        routeReg : new RegExp(path),
        keys
    }
}
function use(route, handler) {
    routes.push([reqRoute(route), handler])
}
use('/users/:pageNumber/:pageSize', (req, res) => res.end(JSON.stringify(req.params)))
use('/user/setting/:id', (req, res) => res.end('user setting: ' + JSON.stringify(req.params)))

http.createServer((req, res) => {
    const pathname = url.parse(req.url).pathname
    for (let i = 0; i < routes.length; i++) {
        const route = routes[i]
        const keys = route[0].keys
        if(keys.length > 0){
            const matchers = route[0].routeReg.exec(pathname)
            if (matchers) {
                const params = {}
                keys.forEach((key,index)=>{
                   params[key] = matchers[index+1]
                })
                req.params = params
                route[1](req, res)
                return
            }
        }
     
    }
    res.end('404')
}).listen(3001)








